import 'dart:io';

import 'package:get/get.dart';
import 'package:handwrite/request/api/CommonApi.dart';
import 'package:handwrite/util/CommonUtil.dart';
import 'package:handwrite/util/PathUtil.dart';

import 'state.dart';

class WriteLogic extends GetxController {
  final WriteState state = WriteState();

  @override
  void onInit() {
    super.onInit();
    state.list.addAll((Get.arguments as String).split(''));
  }

  Future<void> submit() async {
    if (state.signController.value.isEmpty) {
      showToast("请签字");
      return;
    }
    String path = await getCurrentFile();
    try {
      await CommonApi.submit(path, state.list[state.currentIndex.value]);
      showToast("上传成功");
      if (state.currentIndex.value < state.list.length - 1) {
        state.currentIndex.value++;
        state.signController.value.clear();
      } else {
        Get.back(result: true);
      }
    } catch (e) {
      print(e);
    }
    File(path).deleteSync();
  }

  Future<String> getCurrentFile() async {
    var bytes = await state.signController.value.toPngBytes();
    if (bytes == null) {
      showToast("生成图片失败");
      return "";
    }
    var f = File(
        "${await PathUtil.getSignPath()}${DateTime.now().microsecondsSinceEpoch}.png");
    f.writeAsBytesSync(bytes);
    return f.path;
  }
}
